<?php
/**
 * CreateTime: 2023/1/9 10:56
 */

namespace App\Http\Controllers\MeClient;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\DictionaryFunc;
use App\Func\MeDataFunc;
use App\Func\MeLawCaseFunc;
use App\Func\ResponseFunc;
use App\Http\Controllers\Controller;
use App\Http\Requests\ListBasicRequest;
use App\Http\Requests\MeClient\MeClientAddRequest;
use App\Http\Requests\MeClient\SetMeClientLatterRequest;
use App\Models\File\FileModel;
use App\Models\MeClient\MeClientModel;
use App\Models\Staff\StaffModel;
use Illuminate\Support\Facades\Redis;
use JetBrains\PhpStorm\Pure;

class MeClientController extends Controller
{
    private MeClientModel $meClientModel;

    #[Pure] public function __construct()
    {
        $this->meClientModel = new MeClientModel();
    }

    public function addMeClient(MeClientAddRequest $request){
        try {
            // 删除队列
            Redis::del('mediation_client_code_list');
            $data = $request->all();
            // 判断当前委托方是否已经存在
            $nameIsExists = $this->meClientModel->isExistByCondition(
                [
                    'client_name' => $data['client_name'],
                    'status' => BaseConsts::STATUS_NORMAL
                ]
            );
//            if($nameIsExists){
//                return ResponseFunc::returnJson(
//                    'error',
//                    null,
//                    '当前委托方已存在',
//                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
//                );
//            }
            // 判读委托方code是否存在
            $codeIsExists = $this->meClientModel->isExistByCondition(
                [
                    'client_code' => $data['client_code'],
                    'status' => BaseConsts::STATUS_NORMAL
                ]
            );
            if($codeIsExists){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    '当前委托方标识已存在',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS
                );
            }

            // 设置默认值
            $data = MeDataFunc::setDefault($data);
            $data['client_union_id'] = $data['client_code'].date("Ymd");
            return ResponseFunc::returnJson(
                'ok',
                ['client_id' => $this->meClientModel->add($data)],
                '新建委托方成功',
                ResponseStatusConsts::CREATED_201_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '新建委托方失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function editMeClient($clientId){
        try {
            // 删除队列
            Redis::del('mediation_client_code_list');
            $data = request()->all();
            $data['client_id'] = $clientId;
            unset($data['status']);
            unset($data['owner_id']);
            if(isset($data['client_name'])){
                $existsId = $this->meClientModel->getByName($data['client_name'],['client_id'])['client_id'] ?? 0;
//                if($existsId && ($existsId != $clientId)){
//                    return ResponseFunc::returnJson(
//                        'error',
//                        null,
//                        '当前委托方已存在',
//                        ResponseStatusConsts::OK_200_RESPONSE_STATUS
//                    );
//                }
            }
            $this->meClientModel->updateData($data);
            return ResponseFunc::returnJson(
                'ok',
                null,
                '编辑委托方成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '编辑委托方失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function delMeClient($clientId){
        try {
            $data = [
                'client_id' => $clientId,
                'status' => BaseConsts::STATUS_DELETE,
            ];
            $this->meClientModel->updateData($data);
            return ResponseFunc::returnJson(
                'ok',
                null,
                '删除委托方成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '删除委托方失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }

    public function getMeClientInfoById($clientId){
        try {
            $res = $this->meClientModel->getById($clientId) ?? [];
            if($res){
                $res = $this->disposeData($res);
                $res = $this->setMeClientAuth($res);
            }
            return ResponseFunc::returnJson(
                'ok',
                $res,
                '获取委托方详情成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '获取委托方详情失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
    }


    public function setMeClientLatter($clientId){
        $data = request()->all();
        $meClientModel = new MeClientModel();
        try {
            $res = $meClientModel->where('client_id',$clientId)->update([
                'client_temp_law_file_id' => $data['client_temp_law_file_id'] ?? null,
                'client_temp_mediation_file_id' => $data['client_temp_mediation_file_id'] ?? null,
                'client_temp_mediation_agreement_file_id' => $data['client_temp_mediation_file_id'] ?? null,
                'client_temp_law_not_sign_file_id' => $data['client_temp_law_not_sign_file_id'] ?? null,
            ]);
            return ResponseFunc::returnJson(
                'ok',
                null,
                '设置调解函配置成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '设置调解函配置失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

    }

    public function getMeClientLatter($clientId){
        $fileModel = new FileModel();
        $clientInfo = $this->meClientModel->getById($clientId,[
            'client_temp_law_file_id',
            'client_temp_mediation_file_id',
            'client_temp_mediation_agreement_file_id',
            'client_temp_law_not_sign_file_id',
        ]);


        $data = [];
        if($clientInfo){
            foreach($clientInfo->toArray() as $key=>$value){
                $data[$key] = $fileModel->getFileById($value);
            }
        }else{
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前委托方不存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        return ResponseFunc::returnJson(
            'ok',
            $data,
            '获取调解函配置成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );

    }


    public function getMeClientList(ListBasicRequest $request){
        try {
            $pFilters = $request->get('filters');
            $pageSize = $request->get('page_size');
            $filters = $pFilters ? json_decode($pFilters,true) : [];
            // 获取公司部门信息
            $query = $this->meClientModel->select([
                'client_id',
                'client_id as key',
                'client_name',
                'client_contacts',
                'client_type',
                'owner_id',
                'client_code',
                'client_import_count',
            ])->where('status',BaseConsts::STATUS_NORMAL);
            if($filters){
                // 如果有这个参数则表示只查询拥有uuid的委托方
                if(isset($filters['only_uuid']) && $filters['only_uuid']){
                    $query = $query->whereNotNull('client_union_id');
                }
                if(isset($filters['client_type']) && $filters['client_type']){
                    $query = $query->where('client_type',$filters['client_type']);
                }
                if(isset($filters['client_name']) && $filters['client_name']){
                    $query = $query->where('client_name','LIKE',"%".$filters['client_name']."%");
                }
                if(isset($filters['client_contacts']) && $filters['client_contacts']){
                    $query = $query->where('client_contacts','LIKE',"%".$filters['client_contacts']."%");
                }
                if(isset($filters['client_code']) && $filters['client_code']){
                    $query = $query->where('client_contacts','LIKE',"%".$filters['client_contacts']."%");
                }
            }
            $data = $this->meClientModel->getList($query,$pageSize)->toArray() ?? [];
            if($data['data']){
                foreach($data['data'] as $key => $value){
                    $data['data'][$key] = $this->disposeData($data['data'][$key]);
                    $data['data'][$key] = $this->setMeClientAuth($data['data'][$key]);
                }
            }
            return ResponseFunc::returnJson(
                'ok',
                $data,
                '获取委托方列表成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }catch (\Exception $exception){
            dd($exception);
            return ResponseFunc::returnJson(
                'error',
                null,
                '获取委托方列表失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

    }

    private function setMeClientAuth($data){
        return $data;
    }

    private function disposeData($data){
        $staffModel = new StaffModel();
        $data['owner_name'] = $staffModel->getStaffDetail($data['owner_id'],['staff_name'])['staff_name'] ?? "-";
        $data['client_type_str'] = DictionaryFunc::getDictionaryInfoByDictionaryId($data['client_type'],['dictionary_name'])['dictionary_name'] ?? "-";
        return $data;
    }






}